package com.linx.common.web.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linx.common.core.utils.HttpClientUtils;
import com.linx.common.core.utils.SpringUtils;
import com.linx.common.redis.utils.RedisUtils;
import com.linx.common.web.properties.JcptHkProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

/***
 * @ClassName HkTokenUtils
 * @Description 海康token工具类
 * @Author gushaoliang
 * @Date 2024/12/19 上午11:02
 * @Version 1.0
 */
@Component
@Slf4j
public class HkTokenUtils {

    private static long tokenExpireTime = 0;
    private static String cachedAccessToken = null;


    public static String url;
    public static String grantType;
    public static String clientId;
    public static String clientSecret;


    public HkTokenUtils() {
        JcptHkProperties jcptHkProperties = SpringUtils.getBean(JcptHkProperties.class);
        url = jcptHkProperties.getUrl();
        grantType = jcptHkProperties.getGrantType();
        clientId = jcptHkProperties.getClientId();
        clientSecret = jcptHkProperties.getClientSecret();
    }

    /**
     * 获取token（缓存机制）
     *
     * @return token
     * @throws Exception 异常
     */
    public String getHkToken() {
        String hkToken = RedisUtils.getCacheObject("hkToken");
            //url = "https://hzerodevgw.ysyec.com/oauth/oauth/token";
            //grantType = "client_credentials";
            //clientId = "hk-client";
            //clientSecret = "123qwe";
            // 解析返回结果
            String response = null;
            try {
                response = HttpClientUtils.sendPost(url + "?grant_type=" + grantType + "&client_id=" + clientId +
                        "&client_secret=" + clientSecret,
                    null);
            } catch (IOException e) {
                throw new RuntimeException("获取海康token失败: " + e.getMessage());
            }
            log.info("统一平台海康认证请求返回:" + response);

            // 解析返回结果
            JSONObject jsonResponse = JSON.parseObject(response);
            if (jsonResponse.containsKey("access_token")) {
                cachedAccessToken = jsonResponse.getString("access_token");

                return cachedAccessToken;
            } else {
                throw new RuntimeException("获取海康token失败: " + jsonResponse);
            }


    }

    public static void main(String[] args) throws Exception {
        String gisToken = new HkTokenUtils().getHkToken();
    }

}
